<template>
    <div>
        <quill-editor 
            v-model="content"
            ref="editor"
            :options="editorOption"
            @change="onChange">
        </quill-editor>
        <Modal v-model="modal" title="图片上传">
          <PictureEditItem :uploadList="uploadList" :maxlength="maxlength" @uploadPic = "uploadPic"></PictureEditItem>  
          <div slot="footer">
            <Button size="large"  @click="modal=false">取消</Button>
            <Button size="large" type="primary" @click="onSavePic">确定</Button>
          </div>
        </Modal>
        <Modal v-model="modalVd" title="视频上传">
          <PictureEditItem :uploadList="vdUploadList" :upLoadType="upLoadType" :maxlength="vdMaxlength" @uploadPic="uploadVd"></PictureEditItem>  
          <div slot="footer">
            <Button size="large"  @click="modalVd=false">取消</Button>
            <Button size="large" type="primary" @click="onSaveVd">确定</Button>
          </div>
        </Modal>
    </div>
</template>
<script>
import PictureEditItem from "./PictureEditItem";
import { mapGetters } from "vuex"
import { 
  getOriginData, 
  uploadImageUrl, 
  uploadFlashUrl, 
  uploadMediaUrl, 
  uploadFileUrl,
  preFixPath} from "@/util"
import { quillEditor, Quill } from "vue-quill-editor"
// import Quill from "quill"
import { container, ImageExtend, QuillWatch} from 'quill-image-extend-module'
Quill.register('modules/ImageExtend', ImageExtend)

export default {
  props: {
    /*编辑器的内容*/
    value: {
      type: String
    },
    /*图片大小*/
    maxSize: {
      type: Number,
      default: 4096 //kb
    }
  },
  
  data() {
    return {
      uploadList: [],
      maxlength: 10,
      modalVd: false,
      vdUploadList: [],
      vdMaxlength: 1,
      upLoadType: 'media',
      content: "",
      index:-1,
      modal:false,
      uploadImageUrl,
      uploadMediaUrl,
      preFixPath,
      toolbarOptions: [
        ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
        ['blockquote', 'code-block'],
        [{ 'header': 1 }, { 'header': 2 }],               // custom button values
        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
        [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
        [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
        [{ 'direction': 'rtl' }],                         // text direction

        [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

        [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
        [{ 'font': [] }],
        [{ 'align': [] }],
        ['clean']                                         // remove formatting button
      ],
      uploadList:[],
      uploadMax: SYSTEM_CONFIG.uploadMaxSize * 1024 * 1024,
      videoUrl:'',
      headers: {},
      editorOption: {
        modules: {
          ImageExtend: {
            loading: true,
            name: "file",
						size: 4,  // 可选参数 图片大小，单位为M，1M = 1024kb
						action: uploadImageUrl,
            headers: xhr => {
              //关键是这句话
              xhr.setRequestHeader("Authorization",'Bearer '+ this.user.userToken);
              return xhr; //    Authorization:localStorage.getItem("sessionKey")
						}, // 可选参数 设置请求头部
						sizeError: () => {console.log('图片超过大小了')},  // 图片超过大小的回调
						start: () => {console.log('开始')},  // 可选参数 自定义开始上传触发事件
						end: () => {console.log('结束')},  // 可选参数 自定义上传结束触发的事件，无论成功或者失败
						error: () => {console.log('错误')},  // 可选参数 上传失败触发的事件
						success: (e) => {
							this.onFileChange.bind(this);
						},  // 可选参数  上传成功触发的事件
            response: res => {
              return res.data.urlPrefix + res.data.path;
						},
						change: (xhr, formData) => {
							// xhr.setRequestHeader('myHeader','myValue')
              // formData.append('token', 'myToken')
						} // 可选参数 每次选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
          },
          toolbar: {
              container:  [['bold', 'italic', 'underline', 'strike'],
                          ['blockquote', 'code-block'],
                          [{'header': 1}, {'header': 2}],
                          [{'list': 'ordered'}, {'list': 'bullet'}],
                          [{'script': 'sub'}, {'script': 'super'}],
                          [{'indent': '-1'}, {'indent': '+1'}],
                          [{'direction': 'rtl'}],
                          [{'size': ['small', false, 'large', 'huge']}],
                          [{'header': [1, 2, 3, 4, 5, 6, false]}],
                          [{'color': []}, {'background': []}],
                          [{'font': []}],
                          [{'align': []}],
                          [{'clean':'源码编辑'}],
                          ['link', 'image', 'video']],
              handlers: {
                'code-block': function(){
                  const container = this.container;
                  const firstChild = container.nextElementSibling.firstChild;
                  if(!this.shadeBox){
                    let shadeBox = this.shadeBox = document.createElement('div');
                    shadeBox.style.cssText = 'position:absolute; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); cursor:pointer';
                    container.style.position  = 'relative';
                    shadeBox.addEventListener('click',function(){
                      this.style.display = 'none';
                      firstChild.innerHTML = firstChild.innerText.trim();
                    },false);
                    container.appendChild(shadeBox);
                    firstChild.innerText = firstChild.innerHTML;
                  }else {
                    this.shadeBox.style.display = 'block';
                    firstChild.innerText = firstChild.innerHTML;
                  }
                },
                'image':()=> {
                  this.index = this.editor.getSelection().index;
                  this.modal = true;
                },
                'video':(v)=>{
                  this.videoClick();
                  // this.index = this.editor.getSelection().index;
                  // this.modalVd = true;
                }
              }
          }
        },
        placeholder: "请输入文本",
        scrollingContainer: "div"
      }
    };
  },
  methods: {
    initButton() {      //在使用的页面中初始化按钮样式
      // const sourceEditorButton = document.querySelector('.ql-sourceEditor');
      // sourceEditorButton.style.cssText = "width:80px; border:1px solid #ccc; border-radius:5px;";
      // sourceEditorButton.innerText="源码编辑";
    },
    addMyBlot() {},
    uploadVd(val){
      this.vdUploadList = val;
    },
    uploadPic(val){
      this.uploadList = val
    },
    onChange() {
      this.$emit("input", this.content);
    },
    onSavePic(){
      this.uploadList.forEach(item =>{
        this.editor.insertEmbed(this.index, 'image', item.url.urlPrefix + item.url.path);
        this.index++;
      })
      this.modal = false;
      this.uploadList = [];
    },
    onSaveVd(){
      this.vdUploadList.forEach(item =>{
        this.editor.insertEmbed(this.index, 'video', item.url.urlPrefix + item.url.path);
        this.index++;
      })
      this.modalVd = false;
      this.vdUploadList = [];
    },
    videoClick() {
      /*创建input file*/
      var input = document.createElement('input');
      input.type = 'file';
      input.name = this.fileName;
      input.accept = this.accept;
      input.onchange = this.onFileChange.bind(this);
      input.click();
    },
    /*选择上传视频*/
    onFileChange(e) {
      var fileInput = e.target;
      if (fileInput.files.length == 0) {
          return;
      }
      
      if (this.uploadMax >0 && fileInput.files[0].size > this.uploadMax) {
          this.$Notice.warning({
              title: '超出文件大小限制',
              desc: '文件 ' + fileInput.files[0].name + ' 太大，不能超过 '+ parseInt(this.uploadMax/1024)+'M。'
          });
          return;
      }
      var self = this;
      var data = new FormData();
      data.append('file', fileInput.files[0], fileInput.files[0].name);
      this.editor.focus();
      var xhr = new XMLHttpRequest();
      xhr.open('post', this.uploadMediaUrl);
      xhr.setRequestHeader("Authorization",'Bearer '+ this.user.userToken);
      xhr.responseType='json';
      xhr.send(data);
      xhr.onload = function(e, ) {
        let res = xhr.response;
        if (typeof res === 'string') {
            res = JSON.parse(res);
        }
        if(res.code === 200){
            self.editor.insertEmbed(self.editor.getSelection().index, 'video', res.data.urlPrefix+res.data.path);
        } else {
            self.$Notice.error({
                title: '上传失败',
                desc: res.message
            })
        }
      }
    },
  },
  components: {
    quillEditor,
    PictureEditItem
  },
  mounted() {
    this.initButton()
    this.content = this.value;
    let userToken = this.user.userToken
    if (userToken){
      this.headers['Authorization'] = 'Bearer ' + `${userToken}`;
    }
  },
  computed: {
    editor() {
      return this.$refs.editor.quill;
		},
    ...mapGetters(['user']),
    url() {
      let urlStr = this.uploadMediaUrl
      return urlStr
    },
    accept() {
      let acceptStr = SYSTEM_CONFIG.uploadMediaExtension.split(',').map(item => 'video/'+item).join(',');
      return acceptStr
    },
    format() {
      let  formatArr = SYSTEM_CONFIG.uploadMediaExtensions
      return formatArr
    }
  },
  watch: {
    value(newVal, oldVal) {
      if (this.editor) {
        if (newVal !== this.content) {
          this.content = newVal;
        }
      }
    }
  }
};
</script>
<style>
.ql-snow .ql-tooltip{
	left: 0 !important;
}

</style>
